package com.biovr.backend.restcontroller;

import com.biovr.backend.domain.ExpirementReport;
import com.biovr.backend.domain.PublishMessage;
import com.biovr.backend.repository.ExpirementReportRepository;
import com.biovr.backend.service.ExpmReportService;
import com.biovr.backend.utils.DateTimeUtils;
import com.biovr.backend.utils.ResponseFactory;
import com.biovr.backend.utils.RestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by monodev on 2017/6/7.
 */
@Api(value = "/expmreport",description = "实验报告API", consumes="application/json")
@RestController
@RequestMapping("/expmreport")
public class ExpirementReportController {

    @Autowired
    private ExpirementReportRepository expirementReportRepository;
    @Autowired
    private  DateTimeUtils dateTimeUtils;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ExpmReportService expmReportService;

    @GetMapping
    public RestResponse<List<ExpirementReport>> getAll(){
        return ResponseFactory.createSuccessResult(expirementReportRepository.findAll());
    }
    @GetMapping("/status")
    public RestResponse<List<ExpirementReport>> getByStatus(@RequestParam String status){
        String [] strs=null;
        if(status.contains("_")){
           strs=  status.split("_");
        }
        if(null!=strs){
            return ResponseFactory.createSuccessResult(expirementReportRepository.findByStatusIn(strs));
        }
        else{
            return ResponseFactory.createSuccessResult(expirementReportRepository.findByStatusIn(status));
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value="根据id查找实验报告",response = ExpirementReport.class)
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "string",paramType = "path")
    public RestResponse<ExpirementReport> getById(@PathVariable String id){
        ExpirementReport expirementReport = expirementReportRepository.findOne(id);
        return ResponseFactory.createRestResponse(true,"",expirementReport);
    }


    /**
     * 根据学生Id查找
     * @param id
     * @return
     */
    @ApiOperation(value="根据学生Id查找实验报告",notes = "必须传入/stu/{id}",response = ExpirementReport.class,responseContainer = "List")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "string",paramType = "path")
    @GetMapping("/stu/{id}")
    public RestResponse<List<ExpirementReport>> getByStudentId(@PathVariable String id){
        List<ExpirementReport> expirementReports = expirementReportRepository.findByUserId(new ObjectId(id));
        return ResponseFactory.createRestResponse(true,"",expirementReports);
    }

    /**
     * 根据学生Id和实验id查找单个项目
     * @param expmId
     * @param stuId
     * @return
     */
    @GetMapping("/expm/{expmId}")
    public RestResponse<ExpirementReport> getByStudentIdAndExpmId(@PathVariable String expmId, @RequestParam String stuId){
        Query query = new Query(where("expmId").is(expmId).and("user.id").is(new ObjectId(stuId)));
         ExpirementReport report = mongoTemplate.findOne(query,ExpirementReport.class);
        return ResponseFactory.createSuccessResult(report);
    }


      //   @Query("{ 'school._id': ?0, 'major._id': ?1,'klass._id':?2,'grade._id':?3,'expmId':?4")

    /**
     * 根据实验、学校信息查找
     * @param expmId
     * @param schoolId
     * @param majorId
     * @param gradeId
     * @param klassId
     * @return
     */
    @GetMapping("/expm/{expmId}/schoolInfo")
    public  RestResponse<List<ExpirementReport>> getByExpmAndSchoolInfo(
      @PathVariable String expmId,
      @RequestParam String schoolId,
      @RequestParam String majorId,
      @RequestParam String gradeId,
      @RequestParam String klassId
    ){
//        List<ExpirementReport> results = expirementReportRepository.findBySchoolInfo(schoolId,  new ObjectId(majorId),  new ObjectId(klassId), new ObjectId(gradeId), expmId);
//        return ResponseFactory.createSuccessResult(results);

         Query query = new Query(
          where("expmId").is(expmId)
            .and("user.schoolId").is(schoolId)
            .and("user.stuMajor.id").is(new ObjectId(majorId))
            .and("user.stuGrade.id").is(new ObjectId(gradeId))
          .and("user.stuClass.id").is(new ObjectId(klassId))
                 .and("status").in(new Object[]{"submitted","viewed"})
        );

        List<ExpirementReport> reports = mongoTemplate.find(query,ExpirementReport.class);
        return ResponseFactory.createSuccessResult(reports);

    }
    /**
     * 新增实验报告
     * @param expirementReport
     * @return
     */
    @ApiOperation(value="新增实验报告",notes = "json格式",response = PublishMessage.class)
    @ApiImplicitParam(name = "expirementReport", value = "新增ExpirementReport对象，注意user字段不能为空", required = true, dataType = "ExpirementReport")
    @PostMapping
    public RestResponse<ExpirementReport> addSaveReport(@RequestBody ExpirementReport expirementReport) throws Exception{

        if(expirementReport.getStatus()=="submitted"){
            return ResponseFactory.createErrorResult("此报告已提交，不能重复提交");
        }
        if(expirementReport.getUser()==null){
            return ResponseFactory.createRestResponse(false,"学生不能为空",null);
        }
        //初次提交设定提交时间
        if(null==expirementReport.getId()){
            expirementReport.setReportTime(dateTimeUtils.getCurrDateTimeString());
        }
        expmReportService.parseImageAndUpload(expirementReport.getContent());

        ExpirementReport report  = expirementReportRepository.insert(expirementReport);
        return ResponseFactory.createRestResponse(true,"",report);
    }

    /**
     * 修改实验报告
     * @param id
     * @param report
     * @return
     * @throws Exception
     */
    @PutMapping("/{id}")
    public RestResponse<ExpirementReport> updateSaveReport(@PathVariable String id,@RequestBody ExpirementReport report) throws Exception{
        report.setId(id);
        if(report.getStatus().equals("viewed")){
            report.setViewTime(dateTimeUtils.getCurrDateTimeString());
        }
        expmReportService.parseImageAndUpload(report.getContent());
        return ResponseFactory.createSuccessResult( expirementReportRepository.save(report));
    }

    /**
     * 删除实验报告
     * @param id
     * @return
     * @throws Exception
     */
    @DeleteMapping("/{id}")
    public  RestResponse<?> delReport(@PathVariable String id) throws Exception{
        ExpirementReport report = expirementReportRepository.findOne(id);
        if(report==null){
            return ResponseFactory.createErrorResult("报告不存在");
        }
        expirementReportRepository.delete(report);
        return ResponseFactory.createSuccessResult();
    }
}
